let express = require('express')
let router = express.Router()
let fs = require('fs')
let path = require('path')
let bcrypt = require('../../utils/bcrypt')

router.post('/',(req,res,next)=>{
  //1.获取参数
  let {username,password,nikename} = req.body;

  //3. 整理参数
  let follow = 0
  let fans = 0
  let time = Date.now()
  nikename = nikename || '系统生成'//npm下个包

  let icon = '/upload/default.jpg'

  if(req.files && req.files.length>0){
    //更名
    fs.renameSync(
      req.files[0].path,
      req.files[0].path  + path.parse(req.files[0].originalname).ext
    )
    icon = '/upload/user/' + req.files[0].filename  + path.parse(req.files[0].originalname).ext
  }

  //2.设定必传参数
  if(!username || !password){
    res.send({
      err:1,msg:'用户名或者密码为必传参数'
    })
    
    if(icon.indexOf('default') === -1){
      fs.unlinkSync('public' +  icon )
    }

    return;
  }

  //4 兜库
  req.mgdb.open({collectionName:'user'}).then(
    ({collection,client})=>{
      //查看用户名是否重复
      collection.find({username}).toArray((err,result)=>{
        if(err){
          res.send({err:1,msg:'集合操作失败'})
          client.close()
        }else{
          if(result.length === 0){
            //密码加密  参数入库
            password = bcrypt.hashSync(password);

            collection.insertOne({
              username,password,follow,fans,nikename,icon,time
            },(err,result)=>{
              if(err){
                res.send({err:1,msg:"注册失败，请重试"})
                if(icon.indexOf('default') === -1){
                  fs.unlinkSync('/public'+ icon )
                }
              }else{
                delete result.ops[0].username
                delete result.ops[0].password
                res.send({err:0,msg:'注册成功',data:result.ops[0]})
              }
              client.close()
            })

          }else{
            res.send({err:1,msg:"该用户已存在"})
            if(icon.indexOf('default') === -1){
              fs.unlinkSync('public' +  icon )
            }
            client.close()
          }
        }
      })
    }
  )

})

module.exports=router;